package cn.sms.org.controller;

import cn.sms.basic.util.AjaxResult;
import cn.sms.basic.util.PageList;
import cn.sms.org.domain.Department;
import cn.sms.org.query.DepartmentQuery;
import cn.sms.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService iDepartmentService;

    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return iDepartmentService.queryById(id);
    }

    @GetMapping
    public List<Department> queryAll(){
        return iDepartmentService.queryAll();
    }

    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long id){
        try {
            iDepartmentService.remove(id);
            return AjaxResult.me();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }

    }

    @PutMapping
    public AjaxResult save(@RequestBody Department department){
        try {
            if (department.getId()==null){
                iDepartmentService.add(department);
            }else {
                iDepartmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    @PostMapping("/list")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query, HttpServletRequest request){
        System.out.println(request.getHeader("token"));
        return iDepartmentService.queryPage(query);
    }

    @PatchMapping
    public AjaxResult batchRemoveDepartment(@RequestBody List<Long> ids){
        try {
            iDepartmentService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }

    @GetMapping("/tree")
    public List<Department> queryTree(){
        return iDepartmentService.queryTree();
    }

}
